package com.yugao.fintech.draper.tenant.context;

import com.yugao.fintech.draper.security.util.SecurityUserUtil;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 多租户上下文过滤器
 */
public class TenantContextWebFilter extends OncePerRequestFilter {
	/**
	 * 保存租户信息到上下文
	 */
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		// 获取请求携带的租户id
		Long tenantId = SecurityUserUtil.getTenantId(request);
		if (Objects.nonNull(tenantId)) {
			// 保存租户id到上下文
			TenantContextHolder.setTenantId(tenantId);
		}
		try {
			chain.doFilter(request, response);
		}
		finally {
			// 清理
			TenantContextHolder.clear();
		}
	}
}